package online.indigo6a.tryspringcloudsecurity.service;

import online.indigo6a.tryspringcloudsecurity.model.LoginUserDetail;
import online.indigo6a.tryspringcloudsecurity.model.User;
import online.indigo6a.tryspringcloudsecurity.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUserName(username);
        if(user==null) {
            throw new UsernameNotFoundException("user not found ,username="+username);
        }
        LoginUserDetail userDetail = new LoginUserDetail();
        userDetail.setUserName(user.getUserName());
        userDetail.setPassword(user.getPasswordHash());
        return userDetail;
    }
    public OidcUserInfo loadOidcUserInfo(String userName) {
        User user = userRepository.findByUserName(userName);
        return OidcUserInfo.builder().subject(userName)
                .address(user.getAddressCity())
                .email(user.getEmail())
                .emailVerified(user.getEmailConfirmed())
                .phoneNumber(user.getPhoneNumber())
                .phoneNumberVerified(user.getPhoneNumberConfirmed())
                .preferredUsername(user.getName())
                .build();

    }
}
